package com.sunyard.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.page.PageMethod;
import com.sunyard.constant.ErrMessageConst;
import com.sunyard.dal.bo.*;
import com.sunyard.dal.bo.device.*;
import com.sunyard.dal.bo.device.key.KeyUploadLogBO;
import com.sunyard.dal.bo.task.OrgBO;
import com.sunyard.dal.bo.task.SingleLockBo;
import com.sunyard.dal.bo.task.TaskFindBO;
import com.sunyard.dal.dto.*;
import com.sunyard.dal.dto.znsTask.OrgDTO;
import com.sunyard.dal.dto.znsTask.OperatorDTO;
import com.sunyard.dal.dto.znsTask.TaskZNSDTO;
import com.sunyard.dal.entity.*;
import com.sunyard.dal.mapper.*;
import com.sunyard.enums.*;
import com.sunyard.manage.apk.Base64Jdk;
import com.sunyard.manage.apk.DataUtilsApk;
import com.sunyard.manage.constant.TblLogConst;
import com.sunyard.manage.constant.TerminalKeyTypeConst;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.manage.service.TerminalService;
import com.sunyard.manage.util.ValidatorUtils;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.Response.HeaderResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import com.sunyard.utils.manage.PageQuery;
import com.sunyard.utils.sm2.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class TerminalServiceImpl implements TerminalService {

    @Autowired
    private TerminalMapper terminalMapper;

    @Autowired
    private TerminalCopyMapper terminalCopyMapper;

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    OrganizationMapper organizationMapper;


    @Autowired
    OperateHistoryMapper operateHistoryMapper;

    @Autowired
    ZNSTaskMapper znsTaskMapper;

    @Autowired
    LockMapper lockMapper;

    @Autowired
    KeyMapper keyMapper;

    @Autowired
    private OperatorLogServiceImpl operatorLogService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private DataUtilsApk dataUtilsApk;

    @Autowired
    private TaskScenarioMapper taskScenarioMapper;

    @Autowired
    private OtherParamMapper otherParamMapper;

    @Autowired
    private PopedomMapper popedomMapper;


    @Override
    public BaseResult<DataGrid<TerminalQueryResDTO>> getTerminalByPage(PaginationBO<TerminalQueryBO> queryBO, HttpServletRequest request) throws Exception {
        TerminalQueryBO terminalQueryBO = queryBO.getParams();
        log.info("终端信息查询入参：{}", JSON.toJSONString(terminalQueryBO));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        Operator operatorLog = operatorMapper.getOperatorByOpId(opId);

        if (StringUtils.isBlank(terminalQueryBO.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            terminalQueryBO.setOrgId(org);
        } else {
            //得到本机构的所有下属机构id号
            String org = getOrgIdAllChild(terminalQueryBO.getOrgId());
            terminalQueryBO.setOrgId(org);
        }
        //设置分页信息
        PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        List<Terminal> terminalList = terminalMapper.getTerminalByPage(terminalQueryBO);
        List<TerminalQueryResDTO> resList = new ArrayList<>();
        for (Terminal terminal : terminalList) {
            TerminalQueryResDTO resDTO = new TerminalQueryResDTO();
            BeanUtil.copyProperties(terminal, resDTO);
            resDTO.setCreateTime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getCreateTime()));
            Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
            resDTO.setOrgName(organization.getOrgName());
            resDTO.setLastSign(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getLastSign()));
            Operator operator = operatorMapper.getOperatorByOpId(terminal.getCreateUser());
            if (ObjectUtil.isNotNull(operator)) {
                resDTO.setCreateUser(operator.getOpName());
            }
            if (!StringUtils.isEmpty(terminal.getTrunkLockOne())) {
                Terminal terminal1 = terminalMapper.selectByPrimaryKey(Integer.valueOf(terminal.getTrunkLockOne()));
                resDTO.setTrunkLockOne(terminal1.getName());
            }
            if (!StringUtils.isEmpty(terminal.getTrunkLockTwo())) {
                Terminal terminal1 = terminalMapper.selectByPrimaryKey(Integer.valueOf(terminal.getTrunkLockTwo()));
                resDTO.setTrunkLockOne(terminal1.getName());
            }
            resList.add(resDTO);
        }
        DataGrid dataGrid = PageQuery.getDataGrids(terminalList, resList);
        operatorLogService.insert("查询设备信息", "查询设备", "1", opId, operatorLog.getOpName(), orgId);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<TerminalQueryResDTO> getTerminalByMac(TerminalMacBO terminalMacBO, HttpServletRequest request) {
        Terminal terminal = terminalMapper.getTerminalByMac(terminalMacBO.getTerminalMac());
        TerminalQueryResDTO resDTO = new TerminalQueryResDTO();
        BeanUtil.copyProperties(terminal, resDTO);
        resDTO.setCreateTime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getCreateTime()));
        Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
        resDTO.setOrgName(organization.getOrgName());
        resDTO.setLastSign(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getLastSign()));
        Operator operator = operatorMapper.getOperatorByOpId(terminal.getCreateUser());
        if (ObjectUtil.isNotNull(operator)) {
            resDTO.setCreateUser(operator.getOpName());
        }
        if (!StringUtils.isEmpty(terminal.getTrunkLockOne())) {
            Terminal terminal1 = terminalMapper.selectByPrimaryKey(Integer.valueOf(terminal.getTrunkLockOne()));
            resDTO.setTrunkLockOne(terminal1.getName());
        }
        if (!StringUtils.isEmpty(terminal.getTrunkLockTwo())) {
            Terminal terminal1 = terminalMapper.selectByPrimaryKey(Integer.valueOf(terminal.getTrunkLockTwo()));
            resDTO.setTrunkLockOne(terminal1.getName());
        }
        return GetResult.getResult(resDTO);
    }

    public void addImportTerminal(TerminalAddBO addBO, HttpServletRequest request) throws Exception {
        log.info("批量添加终端信息的入参为{}", JSON.toJSONString(addBO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String org = getOrgIdAllChild(orgId);
        String[] orgIds = org.split(",");
        int flag = 0;
        for (String id : orgIds) {
            if (id.equals(addBO.getOrgId())) {
                flag++;
            }
        }
        if (flag == 0) {
            throw new Exception("所属机构不是当前机构或下属机构");
        }
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        //判断终端名称是否已经存在
      /*  Terminal terminal = terminalMapper.getTerminalByName(addBO.getName(), null);
        if (ObjectUtil.isNotNull(terminal)) {
            throw new Exception("终端名称已存在");
        }*/
        Terminal terminal = new Terminal();
        BeanUtil.copyProperties(addBO, terminal);
        //给终端的lastTime赋予一个初始值
        terminal.setLastTime("0");
        //判断添加类型是钥匙终端还是锁终端
        if (TerminalTypeEnum.KEY.getCode().equals(addBO.getType())) {
            if (StringUtils.isBlank(addBO.getKeyType())) {
                throw new Exception("钥匙种类不能为空");
            }
            if ("2".equals(addBO.getKeyType())) {
                // 物联网钥匙有电子围栏属性 必填
                if (StringUtils.isBlank(addBO.getOverUser())) {
                    throw new Exception("是否超出电子围栏使用不能为空");
                }
                if (!"1".equals(addBO.getOverUser()) && !"2".equals(addBO.getOverUser())) {
                    throw new Exception("是否超出电子围栏使用只能是1或2");
                }
            } else {
                // 非物联网钥匙
                terminal.setOverUser("");
                addBO.setOverUser("");
            }
            // if (StringUtils.isBlank(addBO.getOverUser())){
            //     addBO.setOverUser("1");
            // }
            if (StringUtils.isBlank(addBO.getMac())) {
                throw new Exception("mac不能为空");
            }
            Terminal terminalByMac = terminalMapper.getTerminalByMac(addBO.getMac());
            if (ObjectUtil.isNotNull(terminalByMac)) {
                throw new Exception("mac地址已存在");
            }
            int keyType = Integer.parseInt(addBO.getKeyType());
            if (keyType > 4) {
                throw new Exception("钥匙种类只能是1,2,3,4");
            }
            terminal.setLastTime("0");
        } else if (TerminalTypeEnum.LOCK.getCode().equals(addBO.getType())) {
            if (LockTypeEnum.EMPLOYEE.getCode().equals(addBO.getLockType())) {
                if (StringUtils.isBlank(addBO.getAdminId())) {
                    throw new Exception("请选择柜员");
                }
                Operator operator1 = operatorMapper.getOperatorByOpId(addBO.getAdminId());
                if (ObjectUtil.isNull(operator1)) {
                    throw new Exception("所选柜员不存在");
                }
                if (!addBO.getOrgId().equals(operator1.getOrgId())) {
                    throw new Exception("所选机构下无所选柜员");
                }
                com.sunyard.dal.dto.OperatorDTO addOperatorDTOByOpId = operatorMapper.getOperatorDTOByOpId(addBO.getAdminId());
                int popedom = popedomMapper.findPopedomByroleId(addOperatorDTOByOpId.getRoleId());
                if (popedom == 0) {
                    throw new Exception("所选柜员没有开锁权限！");
                }
            }
            if (StringUtils.isBlank(addBO.getLockType())) {
                throw new Exception("锁类型不能为空");
            }
            if (!"1".equals(addBO.getLockType()) && !"2".equals(addBO.getLockType()) && !"3".equals(addBO.getLockType())) {
                throw new Exception("锁类型只能是1或2或3");
            }
            Integer count = taskScenarioMapper.selectCount(addBO.getMissionType());
            if (count <= 0) {
                throw new Exception("锁场景不存在");
            }
            if (!"1".equals(addBO.getReversion()) && !"2".equals(addBO.getReversion())) {
                throw new Exception("日志翻转只能是1或2");
            }
            if (!"0".equals(addBO.getJumpLock()) && !"1".equals(addBO.getJumpLock())) {
                throw new Exception("是否跳梁锁只能是0或1");
            }
            terminal.setLockStatus(LockStatusEnum.DISABLE.getCode());
            terminal.setIsInit("0");
        } else if (TerminalTypeEnum.TRUNK.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getTrunkType())) {
                throw new Exception("尾箱种类不能为空");
            }
            if ("0".equals(addBO.getTrunkType())) {
                if (StringUtils.isEmpty(addBO.getImeiid())) {
                    throw new Exception("请选择imei号");
                }
            }
            if (StringUtils.isEmpty(addBO.getEmailid())) {
                throw new Exception("电子标签不能为空");
            }
            if (StringUtils.isEmpty(addBO.getTrunkMissionType())) {
                throw new Exception("尾箱场景不能为空");
            }
            Integer count = taskScenarioMapper.selectCount(addBO.getTrunkMissionType());
            if (count <= 0) {
                throw new Exception("尾箱场景不存在");
            }
            if (StringUtils.isEmpty(addBO.getTaskStatus())) {
                throw new Exception("尾箱状态不能为空");
            }
            if (StringUtils.isEmpty(addBO.getTrunkSn())) {
                throw new Exception("尾箱编号不能为空");
            }
            if (!"0".equals(addBO.getTrunkType()) && !"1".equals(addBO.getTrunkType())) {
                throw new Exception("尾箱种类只能是0或1");
            }
            if (!"0".equals(addBO.getTaskStatus()) && !"1".equals(addBO.getTaskStatus()) && !"2".equals(addBO.getTaskStatus())) {
                throw new Exception("尾箱状态只能是0或1或2");
            }
            if (!"1".equals(addBO.getOverUser()) && !"2".equals(addBO.getOverUser())) {
                throw new Exception("是否超出电子围栏使用只能是1或2");
            }
            //eb8e9013d9d04b539bbfc4406dbe98ba   869768043263047
            //如果是普通尾箱
            if ("1".equals(addBO.getTrunkType())) {
//                List<Terminal> list = terminalMapper.queryByTrunkType(addBO.getTrunkLockOne(), addBO.getTrunkLockTwo());
//                if ("1".equals(list.get(0).getLockType()) && "2".equals(list.get(1).getLockType())) {
//
//                } else if ("1".equals(list.get(0).getLockType()) && "3".equals(list.get(1).getLockType())) {
//
//                } else if ("2".equals(list.get(0).getLockType()) && "1".equals(list.get(1).getLockType())) {
//
//                } else if ("3".equals(list.get(0).getLockType()) && "1".equals(list.get(1).getLockType())) {
//
//                } else {
//                    throw new Exception("锁类型绑定类型有误");
//                }
            } else {
                if (addBO.getTrunkSn().length() != 32 || addBO.getImeiid().length() != 15) {
                    log.info("长度为{}，{}", addBO.getTrunkSn().length(), addBO.getImeiid().length());
                    throw new Exception("尾箱编号为32位，imei号为15位，请核查后重新输入");
                }
            }
            terminal.setTrunkSn(addBO.getTrunkSn());
            terminal.setTrunkLockOne(addBO.getTrunkLockOne());
            terminal.setTrunkLockTwo(addBO.getTrunkLockTwo());
            Terminal terminal1 = terminalMapper.queryTrunkSn(addBO.getTrunkSn());
            if (ObjectUtil.isNotNull(terminal1)) {
                throw new Exception("尾箱编号已存在");
            }
            terminal.setElectricity("0");
            //添加是锁状态默认关闭
            terminal.setDoorStatus(LockStatusEnum.ENABLE.getCode());
            terminal.setLockStatusOne(LockStatusEnum.ENABLE.getCode());
            terminal.setLockStatusTwo(LockStatusEnum.ENABLE.getCode());
            terminal.setOpenStatus(LockStatusEnum.ENABLE.getCode());

        } else if (TerminalTypeEnum.PDA.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getImeiid())) {
                throw new Exception("pda的imel号不能为空");
            }
            if (StringUtils.isEmpty(addBO.getPdatype())) {
                throw new Exception("pda类型不能为空");
            }
            if (StringUtils.isEmpty(addBO.getPdaid())) {
                throw new Exception("pda编号不能为空");
            }
            Terminal terminal1 = terminalMapper.queryPdaId(addBO.getPdaid());
            if (ObjectUtil.isNotNull(terminal1)) {
                throw new Exception("pda编号已存在");
            }
            if (!"1".equals(addBO.getOverUser()) && !"2".equals(addBO.getOverUser())) {
                throw new Exception("是否超出电子围栏使用只能是1或2");
            }
        } else if (TerminalTypeEnum.RFID.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getRfidsn())) {
                throw new Exception("rfid编号不能为空");
            }
            Terminal terminal1 = terminalMapper.queryRfid(addBO.getRfidsn());
            if (ObjectUtil.isNotNull(terminal1)) {
                throw new Exception("rfid编号已存在");
            }
        }
        //添加终端时设置终端状态为停用状态
        terminal.setStatus(StatusEnum.DISABLE.getCode());
        terminal.setCreateUser(opId);
        terminal.setCreateTime(new Date());
        terminal.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        Integer terminalId = null;
        terminalMapper.insert(terminal);
        terminalId = terminalMapper.getLastInsertId();
        terminalMapper.updateTerminalSn(terminalId);
        String logName = "新增设备";
        if ("0".equals(terminal.getType())) {
            logName = TblLogConst.KEY_ADD;
        } else if ("1".equals(terminal.getType())) {
            logName = TblLogConst.LOCK_ADD;
        } else if ("2".equals(terminal.getType())) {
            logName = "尾箱新增";
        }
        operatorLogService.insert("新增终端，终端编号：" + terminalId, logName, "1", opId, operator.getOpName(), orgId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult addTerminal(TerminalAddBO addBO, HttpServletRequest request) {
        log.info("添加终端信息的入参为{}", JSON.toJSONString(addBO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        //判断终端名称是否已经存在
        /*Terminal terminal = terminalMapper.getTerminalByName(addBO.getName(), null);
        if (ObjectUtil.isNotNull(terminal)) {
            return GetResult.getResultFail("终端名称已存在");
        }*/
        TerminalCopy copy = terminalCopyMapper.getCopyByName(addBO.getName());
        List<String> listKey = new ArrayList<>();
        listKey.add(OtherParam.KEY_ADD_AUTH);
        listKey.add(OtherParam.LOCK_ADD_AUTH);
        List<OtherParamDTO> otherParamsKey = otherParamMapper.queryByKeys(listKey);
        if (!org.springframework.util.CollectionUtils.isEmpty(otherParamsKey)) {
            for (OtherParam otherParam : otherParamsKey) {
                if (OtherParam.KEY_ADD_AUTH.equals(otherParam.getConfKey()) && "0".equals(otherParam.getConfValue())) {
                    addBO.setCheckOpId(opId);
                    addBO.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
                } else if (OtherParam.LOCK_ADD_AUTH.equals(otherParam.getConfKey()) && "0".equals(otherParam.getConfValue())) {
                    addBO.setCheckOpId(opId);
                    addBO.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
                }
            }
        }
        if (ObjectUtil.isNotNull(copy)) {
            return GetResult.getResultFail("该终端名称在添加审核中");
        }
        Terminal terminal = new Terminal();
        BeanUtil.copyProperties(addBO, terminal);
        //判断添加类型是钥匙终端还是锁终端
        if (TerminalTypeEnum.KEY.getCode().equals(addBO.getType())) {
            if (StringUtils.isBlank(addBO.getKeyType())) {
                return GetResult.getResultFail("钥匙种类不能为空");
            }

            int num = terminalMapper.getTerminalName(addBO.getName(), addBO.getType(), addBO.getOrgId(), null);
            if (num > 0) {
                return GetResult.getResultFail("该终端名称已存在");
            }

            if (StringUtils.isBlank(addBO.getMac())) {
                return GetResult.getResultFail("mac不能为空");
            }
            Terminal terminalByMac = terminalMapper.getTerminalByMac(addBO.getMac());
            if (ObjectUtil.isNotNull(terminalByMac)) {
                return GetResult.getResultFail("mac地址已存在");
            }
            Integer terminalCopy = terminalCopyMapper.selectByMac(addBO.getMac(), 1, 0);
            if (terminalCopy > 0) {
                return GetResult.getResultFail("mac地址已存在");
            }

            terminal.setLastTime("0");
        } else if (TerminalTypeEnum.LOCK.getCode().equals(addBO.getType())) {
            int num = terminalMapper.getTerminalName(addBO.getName(), addBO.getType(), addBO.getOrgId(), null);
            if (num > 0) {
                return GetResult.getResultFail("该终端名称已存在");
            }

            if (LockTypeEnum.EMPLOYEE.getCode().equals(addBO.getLockType())) {
                if (StringUtils.isBlank(addBO.getAdminId())) {
                    return GetResult.getResultFail("请选择柜员");
                }
            }
            terminal.setLockStatus(LockStatusEnum.DISABLE.getCode());
            terminal.setIsInit("0");
        } else if (TerminalTypeEnum.TRUNK.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getTrunkType())) {
                return GetResult.getResultFail("尾箱种类不能为空");
            }
            if ("0".equals(addBO.getTrunkType())) {
                if (StringUtils.isEmpty(addBO.getImeiid())) {
                    return GetResult.getResultFail("请选择imei号");
                }
            }
            if (StringUtils.isEmpty(addBO.getEmailid())) {
                return GetResult.getResultFail("电子标签不能为空！");
            }
            if (StringUtils.isEmpty(addBO.getTrunkMissionType())) {
                return GetResult.getResultFail("尾箱场景不能为空");
            }
            if (StringUtils.isEmpty(addBO.getTaskStatus())) {
                return GetResult.getResultFail("尾箱状态不能为空");
            }
            if (StringUtils.isEmpty(addBO.getTrunkSn())) {
                return GetResult.getResultFail("尾箱编号不能为空");
            }
            //eb8e9013d9d04b539bbfc4406dbe98ba   869768043263047
            //如果是普通尾箱
            if ("1".equals(addBO.getTrunkType())) {
                List<Terminal> list = terminalMapper.queryByTrunkType(addBO.getTrunkLockOne(), addBO.getTrunkLockTwo());
                if ("1".equals(list.get(0).getLockType()) && "2".equals(list.get(1).getLockType())) {

                } else if ("1".equals(list.get(0).getLockType()) && "3".equals(list.get(1).getLockType())) {

                } else if ("2".equals(list.get(0).getLockType()) && "1".equals(list.get(1).getLockType())) {

                } else if ("3".equals(list.get(0).getLockType()) && "1".equals(list.get(1).getLockType())) {

                } else {
                    return GetResult.getResultFail("锁类型绑定类型有误！");
                }
            } else {
                if (addBO.getTrunkSn().length() != 32 || addBO.getImeiid().length() != 15) {
                    log.info("长度为{}，{}", addBO.getTrunkSn().length(), addBO.getImeiid().length());
                    // return GetResult.getResultFail("尾箱编号为32位，imei号为15位，请核查后重新输入");
                }
            }
            terminal.setTrunkSn(addBO.getTrunkSn());
            terminal.setTrunkLockOne(addBO.getTrunkLockOne());
            terminal.setTrunkLockTwo(addBO.getTrunkLockTwo());
            Terminal terminal1 = terminalMapper.queryTrunkSn(addBO.getTrunkSn());
            if (ObjectUtil.isNotNull(terminal1)) {
                return GetResult.getResultFail("尾箱编号已存在");
            }
            terminal.setElectricity("0");
            //添加是锁状态默认关闭
            terminal.setDoorStatus(LockStatusEnum.ENABLE.getCode());
            terminal.setLockStatusOne(LockStatusEnum.ENABLE.getCode());
            terminal.setLockStatusTwo(LockStatusEnum.ENABLE.getCode());
            terminal.setOpenStatus(LockStatusEnum.ENABLE.getCode());

        } else if (TerminalTypeEnum.PDA.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getImeiid())) {
                return GetResult.getResultFail("pda的imel号不能为空！");
            }
            if (StringUtils.isEmpty(addBO.getPdatype())) {
                return GetResult.getResultFail("pda类型不能为空！");
            }
            if (StringUtils.isEmpty(addBO.getPdaid())) {
                return GetResult.getResultFail("pda编号不能为空！");
            }
            Terminal terminal1 = terminalMapper.queryPdaId(addBO.getPdaid());
            if (ObjectUtil.isNotNull(terminal1)) {
                return GetResult.getResultFail("pda编号已存在");
            }
        } else if (TerminalTypeEnum.RFID.getCode().equals(addBO.getType())) {
            if (StringUtils.isEmpty(addBO.getRfidsn())) {
                return GetResult.getResultFail("rfid编号不能为空");
            }
            Terminal terminal1 = terminalMapper.queryRfid(addBO.getRfidsn());
            if (ObjectUtil.isNotNull(terminal1)) {
                return GetResult.getResultFail("rfid编号已存在");
            }
        }
        //添加终端时设置终端状态为启用状态
        terminal.setStatus(StatusEnum.ENABLE.getCode());
        terminal.setCreateUser(opId);
        terminal.setCreateTime(new Date());
        terminal.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        Integer terminalId = null;
        //如果是同步审核，则直接添加到信息表
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(addBO.getIsCheck())) {
            terminalMapper.insert(terminal);
            terminalId = terminalMapper.getLastInsertId();
            terminalMapper.updateTerminalSn(terminalId);
        }
        TerminalCopy terminalCopy = new TerminalCopy();
        BeanUtil.copyProperties(terminal, terminalCopy);
        terminalCopy.setTerminalId(terminalId);
        terminalCopy.setAuditType(AuditTypeEnum.ADD.getCode());
        terminalCopy.setCreateTime(new Date());
        //如果设备状态为关闭，不需要审核
        terminalCopy.setIsCheck(addBO.getIsCheck());
        // if (KeyStatusEnum.ENABLE.getCode().equals(terminal.getStatus())) {
        //     terminalCopy.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
        // }
        terminalCopy.setCheckOpId(addBO.getCheckOpId());
        terminalCopy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        terminalCopyMapper.insert(terminalCopy);
        String logName = "新增设备";
        if ("0".equals(terminal.getType())) {
            logName = TblLogConst.KEY_ADD;
        } else if ("1".equals(terminal.getType())) {
            logName = TblLogConst.LOCK_ADD;
        } else if ("2".equals(terminal.getType())) {
            logName = "尾箱新增";
        }
        operatorLogService.insert("新增设备信息:"+terminal.getName(), logName, "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("操作成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateTerminal(TerminalUpdateBO updateBO, HttpServletRequest request) {
        //判断当前终端(类型为锁终端 和尾箱终端判断)是否存在已生效任务,终端名称是否已存在
//        if ("1".equals(updateBO.getType()) || "2".equals(updateBO.getType())) {
//            Map<String, Object> mapParams = new HashMap<>();
//            //获取锁具sn码
//            String terminalSn = updateBO.getTerminalSn();
//            //查询是否有关于该锁具任务
//            Integer count = znsTaskMapper.selectConut(terminalSn);
//            if (count > 0) {
//                return GetResult.getResultFail("修改失败,终端:" + updateBO.getName() + "存在未失效任务");
//            }
//    }

        //判断当前终端名称是否已存在
        if ("0".equals(updateBO.getType()) || "1".equals(updateBO.getType())) {
            int num = terminalMapper.getTerminalName(updateBO.getName(), updateBO.getType(), updateBO.getOrgId(), updateBO.getId());
            if (num > 0) {
                return GetResult.getResultFail("该终端名称已存在");
            }
        }


        // 生效的调拨任务不允许做锁具修改操作
        if ("1".equals(updateBO.getType())) {
            Integer count = znsTaskMapper.selectConutBySn(updateBO.getTerminalSn());
            if (count > 0) {
                return GetResult.getResultFail("修改失败,终端:" + updateBO.getName() + "存在未失效调拨任务");
            }
        }

        List<TerminalCopy> terminalCopyList = terminalCopyMapper.selectByTerminalId(Integer.valueOf(updateBO.getId()));
        if (ObjectUtil.isNotNull(terminalCopyList) && terminalCopyList.size() > 0) {
            return GetResult.getResultFail("修改失败,该终端存在未审核信息");
        }
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(updateBO.getId()));
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("未查询到该终端信息，请核对");
        }
        //判断钥匙名称是否已经存在
        /*Terminal terminalByName = terminalMapper.getTerminalByName(updateBO.getName(), Integer.valueOf(updateBO.getId()));
        if (ObjectUtil.isNotNull(terminalByName)) {
            return GetResult.getResultFail("终端名称已存在");
        }*/
        if (TerminalTypeEnum.KEY.getCode().equals(terminal.getType())) {
            //判断Mac地址是否已经存在
            List<Terminal> checkMac = terminalMapper.selectByMacAndId(updateBO.getMac(), updateBO.getId());
            if (ObjectUtil.isNotNull(checkMac) && checkMac.size() > 0) {
                return GetResult.getResultFail("mac地址已存在");
            }
        }
        //修改锁具机构调用自动删除锁具关联的任务
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(updateBO.getIsCheck()) && TerminalTypeEnum.LOCK.getCode().equals(terminal.getType())) {
            if (!terminal.getOrgId().equals(updateBO.getOrgId())
                    || (StrUtil.isNotBlank(terminal.getMissionType()) && StrUtil.isNotBlank(updateBO.getMissionType()) && !terminal.getMissionType().equals(updateBO.getMissionType()))
                    || (StrUtil.isNotBlank(terminal.getLockType()) && StrUtil.isNotBlank(updateBO.getLockType()) && !terminal.getLockType().equals(updateBO.getLockType()))
                    || (StrUtil.isNotBlank(terminal.getAdminId()) && StrUtil.isNotBlank(updateBO.getAdminId()) && !terminal.getAdminId().equals(updateBO.getAdminId()))
            ) {
                znsTaskMapper.deleteBYSn(terminal.getTerminalSn());
                terminalCopyMapper.deleteByTerId(String.valueOf(terminal.getId()));
            }
        }
        //锁具修改为通用锁设置关联人员为空
        if (LockTypeEnum.EMPLOYEE_GENERAL.getCode().equals(updateBO.getLockType())) {
            terminal.setAdminId(null);
        } else {
            terminal.setAdminId(updateBO.getAdminId());
        }
        terminal.setName(updateBO.getName());
        terminal.setKeyType(updateBO.getKeyType());
        terminal.setLockType(updateBO.getLockType());
        terminal.setOrgId(updateBO.getOrgId());
        terminal.setOverUser(updateBO.getOverUser());
        terminal.setMac(updateBO.getMac());
        terminal.setMissionType(updateBO.getMissionType());
        terminal.setReversion(updateBO.getReversion());
        terminal.setJumpLock(updateBO.getJumpLock());
        terminal.setRemark(updateBO.getRemark());
        terminal.setTrunkType(updateBO.getTrunkType());
        terminal.setImeiid(updateBO.getImeiid());
        terminal.setEmailid(updateBO.getEmailid());
        terminal.setTrunkMissionType(updateBO.getTrunkMissionType());
        terminal.setTaskStatus(updateBO.getTaskStatus());
        terminal.setLockStatusOne(updateBO.getLockStatusOne());
        terminal.setLockStatusTwo(updateBO.getLockStatusTwo());
        terminal.setDoorStatus(updateBO.getDoorStatus());
        terminal.setTrunkSn(updateBO.getTrunkSn());
        terminal.setElectricity(updateBO.getElectricity());
        terminal.setCoordinates(updateBO.getCoordinates());
        terminal.setPdaid(updateBO.getPdaid());
        terminal.setPdatype(updateBO.getPdatype());
        terminal.setRfidsn(updateBO.getRfidsn());
        terminal.setKeyWarn(updateBO.getKeyWarn());
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(updateBO.getIsCheck())) {
            terminalMapper.updateByPrimaryKey(terminal);
        }
        //添加审核信息
        addTerminalCopy(terminal, updateBO.getIsCheck(), updateBO.getCheckOpId(), AuditTypeEnum.UPDATE.getCode());
        String logName = "更新设备";
        if ("0".equals(terminal.getType())) {
            logName = TblLogConst.KEY_UPDATE;
        } else if ("1".equals(terminal.getType())) {
            logName = TblLogConst.LOCK_UPDATE;
        } else if ("2".equals(terminal.getType())) {
            logName = "尾箱修改";
        }
        operatorLogService.insert("更新设备信息:" + terminal.getName(), logName, "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("操作成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult deleteTerminal(TerminalDeleteBO deleteBO, HttpServletRequest request) {
        //判断当前终端(类型为锁终端 和尾箱终端判断)是否存在已生效任务
        //根据id查询当前删除信息
        Map<String, String> stringStringMap = terminalMapper.selectInfoById(deleteBO);
        String terminalSn = stringStringMap.get("terminalSn");
        String type = stringStringMap.get("type");
        String trunkSn = stringStringMap.get("trunkSn");
        if ("1".equals(type)) {
            Integer count = znsTaskMapper.selectConut(terminalSn);
            if (count > 0) {
                return GetResult.getResultFail("删除失败,当前终端存在未失效任务");
            }
        } else if ("2".equals(type)) {
            Integer count = znsTaskMapper.selectConutForTer(trunkSn);
            if (count > 0) {
                return GetResult.getResultFail("删除失败,当前终端存在未失效任务");
            }
        }
        List<TerminalCopy> terminalCopyList = terminalCopyMapper.selectByTerminalId(Integer.valueOf(deleteBO.getId()));
        if (ObjectUtil.isNotNull(terminalCopyList) && terminalCopyList.size() > 0) {
            return GetResult.getResultFail("删除失败,该终端存在未审核信息");
        }
        Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(deleteBO.getId()));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("未查询到该终端信息，请核对");
        }
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(deleteBO.getIsCheck())) {
            terminal.setIsDeleted(IsDeletedEnum.DELETED.getCode());
            terminalMapper.updateByPrimaryKey(terminal);
            znsTaskMapper.deleteBYSn(terminalSn);
            terminalCopyMapper.deleteByTerId(String.valueOf(terminal.getId()));
        }
        //添加审核信息
        String isCheck = deleteBO.getIsCheck();
        if ("2".equals(deleteBO.getIsCheck())) {
            isCheck = IsCheckEnum.NOT_CHECKED.getCode();
        }
        addTerminalCopy(terminal, isCheck, deleteBO.getCheckOpId(), AuditTypeEnum.DELETE.getCode());
        String logName = "删除设备";
        if ("0".equals(terminal.getType())) {
            logName = TblLogConst.KEY_DELETE;
        } else if ("1".equals(terminal.getType())) {
            logName = TblLogConst.LOCK_DELETE;
        } else if ("2".equals(terminal.getType())) {
            logName = "尾箱删除";
        }
        operatorLogService.insert("删除设备信息" + terminal.getName(), logName, "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("操作成功");

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchDeleteTerminal(TerminalBatchDeleteBO deleteBO, HttpServletRequest request) {
        String[] ids = deleteBO.getId().split(",");
        for (String id : ids) {
            TerminalDeleteBO terminalDeleteBO = new TerminalDeleteBO();
            terminalDeleteBO.setId(id);
            terminalDeleteBO.setIsCheck(deleteBO.getAuditType());
            terminalDeleteBO.setCheckOpId(deleteBO.getAuditor());
            BaseResult result = deleteTerminal(terminalDeleteBO, request);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail("删除失败!");
            }
        }
        String message = "1".equals(deleteBO.getAuditType()) ? "删除终端成功！" : "删除终端成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateState(TerminalUpdateStateBO updateStateBO, HttpServletRequest request) {
        String message = "0".equals(updateStateBO.getStatus()) ? "启用" : "停用";
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(updateStateBO.getId()));
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("未查询到该终端信息，请核对");
        }
        List<TerminalCopy> terminalCopyList = terminalCopyMapper.selectByTerminalId(Integer.valueOf(updateStateBO.getId()));
        if (ObjectUtil.isNotNull(terminalCopyList) && terminalCopyList.size() > 0) {
            return GetResult.getResultFail(message + "失败,该终端存在未审核信息");
        }
        String logName = message + "终端";
        if ("0".equals(terminal.getType())) {
            logName = "钥匙" + message;
        } else if ("1".equals(terminal.getType())) {
            logName = "锁具" + message;
        } else if ("2".equals(terminal.getType())) {
            logName = "尾箱" + message;
        }
        operatorLogService.insert("用户" + opName + message + "终端", logName, "1", opId, opName, orgId);
        // 生效的调拨任务不允许做锁具修改操作
        if ("1".equals(terminal.getType()) && "1".equals(updateStateBO.getStatus())) {
            Integer count = znsTaskMapper.selectConutBySn(terminal.getTerminalSn());
            if (count > 0) {
                return GetResult.getResultFail("修改失败,终端:" + terminal.getName() + "存在未失效调拨任务");
            }
        }
        TerminalDeleteBO deleteBO = new TerminalDeleteBO();
        deleteBO.setId(updateStateBO.getId());
        Map<String, String> stringStringMap = terminalMapper.selectInfoById(deleteBO);
        String terminalSn = stringStringMap.get("terminalSn");
        String type = stringStringMap.get("type");
        String trunkSn = stringStringMap.get("trunkSn");
        if ("1".equals(updateStateBO.getIsCheck())) {
            //清除未失效的任务
            znsTaskMapper.deleteBYSn(terminalSn);
        }
        /*if ("1".equals(type)) {
            Integer count = znsTaskMapper.selectConut(terminalSn);
            if (count > 0) {
                return GetResult.getResultFail(message + "失败,当前终端存在未失效任务");
            }
        } else if ("2".equals(type)) {
            Integer count = znsTaskMapper.selectConutForTer(trunkSn);
            if (count > 0) {
                return GetResult.getResultFail(message + "失败,当前终端存在未失效任务");
            }
        }*/
        terminal.setStatus(updateStateBO.getStatus());
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(updateStateBO.getIsCheck())) {
            terminal.setStatus(updateStateBO.getStatus());
            terminalMapper.updateByPrimaryKey(terminal);
        }
        String auditType = "0".equals(updateStateBO.getStatus()) ? AuditTypeEnum.ENABLE.getCode() : AuditTypeEnum.DISABLE.getCode();
        //添加审核信息
        addTerminalCopy(terminal, updateStateBO.getIsCheck(), updateStateBO.getCheckOpId(), auditType);
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(updateStateBO.getIsCheck())) {
            return GetResult.getResultSuccess(message + "成功");
        }
        return GetResult.getResultSuccess(message + "成功,待审核");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult batchUpdateState(TerminalBatchUpdateStateBO updateStateBO, HttpServletRequest request) {
        String[] ids = updateStateBO.getId().split(",");
        for (String id : ids) {
            TerminalUpdateStateBO stateBO = new TerminalUpdateStateBO();
            stateBO.setId(id);
            stateBO.setStatus(updateStateBO.getStatus());
            if ("1".equals(updateStateBO.getAuditType())) {
                stateBO.setIsCheck("1");
            } else {
                stateBO.setIsCheck("0");
            }
            stateBO.setCheckOpId(updateStateBO.getAuditor());
            BaseResult result = updateState(stateBO, request);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        String msg = "0".equals(updateStateBO.getStatus()) ? "启用" : "停用";
        String message = "1".equals(updateStateBO.getAuditType()) ? msg + "成功！" : msg + "成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    @Override
    public BaseResult exportTerminal(PaginationBO<TerminalQueryBO> queryBO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        TerminalQueryBO terminalQueryBO = queryBO.getParams();
        log.info("终端信息查询入参：{}", JSON.toJSONString(terminalQueryBO));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));

        if (StringUtils.isBlank(terminalQueryBO.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            terminalQueryBO.setOrgId(org);
        } else {
            //得到本机构的所有下属机构id号
            String org = getOrgIdAllChild(terminalQueryBO.getOrgId());
            terminalQueryBO.setOrgId(org);
        }
        //设置分页信息
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        Operator operatorLog = operatorMapper.getOperatorByOpId(opId);
        operatorLogService.insert("设备信息导出", "导出设备", "1", opId, operatorLog.getOpName(), orgId);
        //设置分页信息
        List<TerminalExport> terminalList = terminalMapper.getTerminalByCondition(terminalQueryBO);
        String title = "终端信息导出";
        String[] keyHeaders = new String[]{"终端名称", "钥匙种类", "所属机构", "机构名称",
                "mac地址", "是否超出电子围栏使用", "终端状态", "备注", "创建时间", "创建人ID", "创建人名称"};
        String[] lockHeaders = new String[]{"终端名称", "锁种类", "所属机构", "机构名称",
                "锁场景", "柜员id", "日志翻转", "锁状态", "终端状态", "备注", "创建时间", "创建人ID", "创建人名称"};
        String[] trunkHeaders = new String[]{"终端名称", "尾箱种类", "终端状态", "尾箱imei号", "电子标签id", "尾箱场景", "尾箱状态", "尾箱编号", "所属机构", "机构名称", "异常", "电量", "经纬度", "门磁开闭", "门状态", "锁状态1", "锁状态2"};
        String[] pdaHeaders = new String[]{"终端名称", "所属机构号", "机构名称", "imei号", "PDA类型", "PDA编号", "是否超出电子围栏使用", "备注"};
        String[] rfidHeaders = new String[]{"终端名称", "所属机构号", "机构名称", "设备编号", "备注"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] keyType = {"指纹终端", "物联网终端", "屏显钥匙", "金库钥匙"};
        String[] lockType = {"通用锁", "员工单锁"};
        String[] overUse = {"否", "是"};
        String[] reversion = {"不翻转", "翻转"};
        String[] lockStatus = {"开启", "关闭"};
        String[] status = {"启用", "停用"};
        String[] trunkType = {"物联网尾箱", "普通尾箱"};
        String[] taskStatus = {"在途", "在网点", "在金库"};
        String[] trunkStatus = {"开启", "关闭"};
        String[] pdaType = {"手机", "掌机"};
        if (TerminalTypeEnum.KEY.getCode().equals(terminalQueryBO.getType())) {
            dataList = terminalList.stream().map(terminal -> {
                Object[] obj = new Object[keyHeaders.length];
                obj[0] = terminal.getName();
                obj[1] = StringUtils.isNotBlank(terminal.getKeyType()) ? keyType[Integer.parseInt(terminal.getKeyType()) - 1] : null;
                obj[2] = terminal.getOrgId();
                //Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
                obj[3] = StringUtils.isNotBlank(terminal.getOrgName()) ? terminal.getOrgName() : null;
                obj[4] = terminal.getMac();
                if ("1".equals(terminal.getOverUser()) || "2".equals(terminal.getOverUser())) {
                    obj[5] = StringUtils.isNotBlank(terminal.getOverUser()) ? overUse[Integer.parseInt(terminal.getOverUser()) - 1] : null;
                } else {
                    obj[5] = "";
                }
                obj[6] = StringUtils.isNotBlank(terminal.getStatus()) ? status[Integer.parseInt(terminal.getStatus())] : null;
                obj[7] = terminal.getRemark();
                obj[8] = DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getCreateTime());
                obj[9] = terminal.getCreateUser();
                //Operator operator = operatorMapper.getOperatorByOpId(terminal.getCreateUser());
                obj[10] = StringUtils.isNotBlank(terminal.getOpName()) ? terminal.getOpName() : null;
                return obj;
            }).collect(toList());
        } else if (TerminalTypeEnum.LOCK.getCode().equals(terminalQueryBO.getType())) {
            dataList = terminalList.stream().map(terminal -> {
                Object[] obj = new Object[lockHeaders.length];
                obj[0] = terminal.getName();
                obj[1] = StringUtils.isNotBlank(terminal.getLockType()) ? lockType[Integer.parseInt(terminal.getLockType()) - 1] : null;
                obj[2] = terminal.getOrgId();
                //Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
                obj[3] = StringUtils.isNotBlank(terminal.getOrgName()) ? terminal.getOrgName() : null;
                obj[4] = terminal.getMissionType();
                obj[5] = terminal.getAdminId();
                obj[6] = StringUtils.isNotBlank(terminal.getReversion()) ? reversion[Integer.parseInt(terminal.getReversion()) - 1] : null;
                obj[7] = StringUtils.isNotBlank(terminal.getLockStatus()) ? lockStatus[Integer.parseInt(terminal.getLockStatus()) - 1] : null;
                obj[8] = StringUtils.isNotBlank(terminal.getStatus()) ? status[Integer.parseInt(terminal.getStatus())] : null;
                obj[9] = terminal.getRemark();
                obj[10] = DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, terminal.getCreateTime());
                obj[11] = terminal.getCreateUser();
                //Operator operator = operatorMapper.getOperatorByOpId(terminal.getCreateUser());
                obj[12] = StringUtils.isNotBlank(terminal.getOpName()) ? terminal.getOpName() : null;
                return obj;
            }).collect(toList());
        } else if (TerminalTypeEnum.TRUNK.getCode().equals(terminalQueryBO.getType())) {
            //"终端名称", "尾箱种类", "终端状态", "尾箱imei号", "电子标签id", "尾箱场景", "尾箱状态", "尾箱编号", "所属机构", "机构名称", "异常", "电量", "经纬度", "门磁开闭", "门状态", "锁状态1", "锁状态2"
            dataList = terminalList.stream().map(terminal -> {
                Object[] obj = new Object[trunkHeaders.length];
                obj[0] = terminal.getName();
                obj[1] = StringUtils.isNotBlank(terminal.getTrunkType()) ? trunkType[Integer.parseInt(terminal.getTrunkType())] : null;
                obj[2] = StringUtils.isNotBlank(terminal.getStatus()) ? status[Integer.parseInt(terminal.getStatus())] : null;
                obj[3] = terminal.getImeiid();
                obj[4] = terminal.getEmailid();
                obj[5] = terminal.getTrunkMissionType();
                obj[6] = StringUtils.isNotBlank(terminal.getTaskStatus()) ? taskStatus[Integer.parseInt(terminal.getTaskStatus())] : null;
                obj[7] = terminal.getTrunkSn();
                String orgId1d = terminal.getOrgId();
                obj[8] = orgId1d;
                //Organization organization = organizationMapper.getOrganizationByOrgId(orgId1d);
                obj[9] = StringUtils.isNotBlank(terminal.getOrgName()) ? terminal.getOrgName() : null;
                obj[10] = terminal.getTrunkError();
                obj[11] = terminal.getElectricity();
                obj[12] = terminal.getCoordinates();
                //需导出转换为开关文字
                obj[13] = StringUtils.isNotBlank(terminal.getOpenStatus()) ? trunkStatus[Integer.parseInt(terminal.getOpenStatus())] : null;
                obj[14] = StringUtils.isNotBlank(terminal.getDoorStatus()) ? trunkStatus[Integer.parseInt(terminal.getDoorStatus())] : null;
                obj[15] = StringUtils.isNotBlank(terminal.getLockStatusOne()) ? trunkStatus[Integer.parseInt(terminal.getLockStatusOne())] : null;
                obj[16] = StringUtils.isNotBlank(terminal.getLockStatusTwo()) ? trunkStatus[Integer.parseInt(terminal.getLockStatusTwo())] : null;
                return obj;
            }).collect(toList());
        } else if (TerminalTypeEnum.PDA.getCode().equals(terminalQueryBO.getType())) {
            //终端名称", "所属机构号", "机构名称", "imei号", "PDA类型", "PDA编号", "是否超出电子围栏使用", "备注
            dataList = terminalList.stream().map(terminal -> {
                Object[] obj = new Object[pdaHeaders.length];
                obj[0] = terminal.getName();
                obj[1] = terminal.getOrgId();
                //Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
                obj[2] = StringUtils.isNotBlank(terminal.getOrgName()) ? terminal.getOrgName() : null;
                obj[3] = terminal.getImeiid();
                obj[4] = StringUtils.isNotBlank(terminal.getPdatype()) ? lockStatus[Integer.parseInt(terminal.getPdatype())] : null;
                obj[5] = terminal.getPdaid();
                obj[6] = StringUtils.isNotBlank(terminal.getOverUser()) ? overUse[Integer.parseInt(terminal.getOverUser()) - 1] : null;
                obj[7] = terminal.getRemark();
                return obj;
            }).collect(toList());
        } else if (TerminalTypeEnum.RFID.getCode().equals(terminalQueryBO.getType())) {
            //"终端名称", "所属机构号", "机构名称", "设备编号", "备注"
            dataList = terminalList.stream().map(terminal -> {
                Object[] obj = new Object[rfidHeaders.length];
                obj[0] = terminal.getName();
                obj[1] = terminal.getOrgId();
                //Organization organization = organizationMapper.getOrganizationByOrgId(String.valueOf(terminal.getOrgId()));
                obj[2] = StringUtils.isNotBlank(terminal.getOrgName()) ? terminal.getOrgName() : null;
                obj[3] = terminal.getRfidsn();
                obj[4] = terminal.getRemark();
                return obj;
            }).collect(toList());
        }
        OutputStream out = null;
        // 防止中文乱码
        String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
        response.setContentType("octets/stream");
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", headStr);
        out = response.getOutputStream();
        ExcelOutput ex = null;
        //导出钥匙数据
        if (TerminalTypeEnum.KEY.getCode().equals(terminalQueryBO.getType())) {
            ex = new ExcelOutput(title, keyHeaders, dataList);
        } else if (TerminalTypeEnum.LOCK.getCode().equals(terminalQueryBO.getType())) {
            //导出锁数据
            ex = new ExcelOutput(title, lockHeaders, dataList);
        } else if (TerminalTypeEnum.TRUNK.getCode().equals(terminalQueryBO.getType())) {
            //导出尾箱数据
            ex = new ExcelOutput(title, trunkHeaders, dataList);
        } else if (TerminalTypeEnum.PDA.getCode().equals(terminalQueryBO.getType())) {
            //导出尾箱数据
            ex = new ExcelOutput(title, pdaHeaders, dataList);
        } else if (TerminalTypeEnum.RFID.getCode().equals(terminalQueryBO.getType())) {
            //导出尾箱数据
            ex = new ExcelOutput(title, rfidHeaders, dataList);
        }
        long end = System.currentTimeMillis();
        ex.export(out);
        return null;
    }


    @Override
    public  BaseResult uploadLog(KeyUploadLogBO uploadLogBO, HttpServletRequest request) throws ParseException {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        //定义日志信息
        String logName = TblLogConst.UPLOAD_LOG;
        String operationDesc = "用户" + opName + "上传操作日志";
        OperateHistory operateHistory = new OperateHistory();

        //乱码校验
        if (!StringUtils.isNumeric(uploadLogBO.getLockId()) || !StringUtils.isNumeric(uploadLogBO.getUser1()) || !dateStrIsValid(uploadLogBO.getOperateTime())) {
            operatorLogService.insert(operationDesc + "乱码", logName, "1", opId, opName, orgId);
            log.warn(operationDesc + "乱码,入参,{}", uploadLogBO);
            return GetResult.getResultSuccess("上传日志乱码");
        }

        //通过钥匙Mac地址查询钥匙信息
        Terminal key = terminalMapper.getTerminalByMac(uploadLogBO.getMac());
        if (ObjectUtil.isNull(key)) {
            return GetResult.getResultFail("终端不存在");
        }

        //校验重复上传
        //OperateHistory operateHistory1 = new OperateHistory();
        //operateHistory1.setOperateTime(uploadLogBO.getOperateTime());
        //operateHistory1.setMac(uploadLogBO.getMac());
        //operateHistory1.setMissionId(uploadLogBO.getMissionId());
        //operateHistory1.setLockId(uploadLogBO.getLockId());
        //operateHistory1.setLockStatus(uploadLogBO.getLockStatus());
        //operateHistory1.setOperateType(uploadLogBO.getOperateType());
        //operateHistory1.setUser1(uploadLogBO.getUser1());
        //operateHistory1.setUser2(uploadLogBO.getUser2());
        //if ("成功".equals(uploadLogBO.getOperateStatus())) {
        //    operateHistory1.setOperateStatus("1");
        //} else {
        //    operateHistory1.setOperateStatus("2");
        //}
        //Integer count = operateHistoryMapper.selectByMacAndOperateTime(operateHistory1);
        //if (count>0) {
        //    log.warn(operationDesc + ",上传日志重复,入参,{}", uploadLogBO);
        //    return GetResult.getResultSuccess("上传日志重复");
        //}

        if (!key.getKeyType().equals(TerminalKeyTypeConst.KEY_TYPE_4)) {
            //通过任务编号查询是否存在改任务信息
            uploadLogBO.setMissionId(String.format("%09d", Long.parseLong(uploadLogBO.getMissionId())));
            String taskId = String.format("%09d", Long.parseLong(uploadLogBO.getMissionId()));
            TaskZNSDTO taskZNSDTO = znsTaskMapper.selectById(taskId);
            if (ObjectUtil.isNull(taskZNSDTO)) {
                return GetResult.getResultFail("任务不存在");
            }
            operateHistory.setMissionType(taskZNSDTO.getTaskTypeName());
            operateHistory.setMissionId(uploadLogBO.getMissionId());
        } else {
            operateHistory.setMissionType("调拨锁任务");
            operateHistory.setMissionId("");
        }


        operateHistory.setLockStatus(uploadLogBO.getLockStatus());
        if ("成功".equals(uploadLogBO.getOperateStatus())) {
            operateHistory.setOperateStatus("1");
        } else {
            operateHistory.setOperateStatus("2");
        }
        operateHistory.setOperateTime(uploadLogBO.getOperateTime());
        String lockId = uploadLogBO.getLockId().replace("\u0000", "");
        int index = 0;
        for (int i = 0; i < lockId.length(); i++) {
            if ('0' != lockId.charAt(i)) {
                index = i;
                break;
            }
        }
        // Terminal lock = terminalMapper.selectByPrimaryKey(Integer.parseInt(lockId.substring(index)));

        Terminal lock = terminalMapper.getTerminalBySnAndDelete(lockId, TerminalTypeEnum.LOCK.getCode());
        String openLockTime = lock.getOpenLockTime();
        if (ObjectUtil.isNull(lock)) {
            return GetResult.getResultFail("锁具" + lockId + "不存在");
        }

        operateHistory.setOperateType(uploadLogBO.getOperateType());
        if ("2".equals(lock.getReversion())) {
            if ("01-开启".equals(uploadLogBO.getLockStatus())) {
                operateHistory.setOperateType("02-关锁");
                lock.setLockStatus(LockStatusEnum.DISABLE.getCode());

            }
            if ("02-关闭".equals(uploadLogBO.getLockStatus())) {
                operateHistory.setOperateType("01-开锁");
                lock.setLastTime(String.valueOf(System.currentTimeMillis()));
                lock.setLockStatus(LockStatusEnum.ENABLE.getCode());
                if (StringUtils.isNotBlank(openLockTime) ) {
                    if (StringUtils.isNotBlank(uploadLogBO.getOperateTime()) && uploadLogBO.getOperateTime().compareTo(openLockTime) > 0){
                        lock.setOpenLockTime(uploadLogBO.getOperateTime());
                    }
                } else {
                    lock.setOpenLockTime(uploadLogBO.getOperateTime());
                }

            }
        } else {
            if ("01-开启".equals(uploadLogBO.getLockStatus())) {
                operateHistory.setOperateType("01-开锁");
                lock.setLockStatus(LockStatusEnum.ENABLE.getCode());
                lock.setLastTime(String.valueOf(System.currentTimeMillis()));
                if (StringUtils.isNotBlank(openLockTime) ) {
                    if (StringUtils.isNotBlank(uploadLogBO.getOperateTime()) && uploadLogBO.getOperateTime().compareTo(openLockTime) > 0){
                        lock.setOpenLockTime(uploadLogBO.getOperateTime());
                    }
                } else {
                    lock.setOpenLockTime(uploadLogBO.getOperateTime());
                }
            }
            if ("02-关闭".equals(uploadLogBO.getLockStatus())) {
                operateHistory.setOperateType("02-关锁");
                lock.setLockStatus(LockStatusEnum.DISABLE.getCode());
            }
        }
        operateHistory.setLockId(lockId);
        operateHistory.setCollectTime(new Date());
        operateHistory.setUser1(uploadLogBO.getUser1());
        if (StringUtils.isNotBlank(uploadLogBO.getUser2())) {
            operateHistory.setUser2(uploadLogBO.getUser2());
        }
        operateHistory.setKeyId(key.getId());
        operateHistory.setMac(uploadLogBO.getMac());
        operateHistory.setOrgId(key.getOrgId());
        operateHistory.setStatus("1");
        operateHistory.setIsFrom("1");
        Organization organization = organizationMapper.getOrganizationByOrgId(key.getOrgId());
        log.info("日志任务对应机构：{}", JSONUtil.toJsonStr(organization));
        if (organization != null && !"".equals(organization.getOrgWorkingTime())) {
            JSONObject jsonObjectTime = JSON.parseObject(organization.getOrgWorkingTime());
            String date1 = jsonObjectTime.getString("date");
            Long operateDate = DateUtil.String2Long(uploadLogBO.getOperateTime());
            boolean flag = false;
            if (date1.contains(DateUtil.getWeekOfDate(DateUtil.String2Long(uploadLogBO.getOperateTime())))) {
                if (DateUtil.isOntime(DateUtil.String2Long(uploadLogBO.getOperateTime()), jsonObjectTime.getString("startTime"), jsonObjectTime.getString("endTime"))) {
                    flag = true;
                }
            }
            if (flag) {
                operateHistory.setIsWorkTime("1");
            } else {
                operateHistory.setIsWorkTime("2");
            }
        }

        try {
            operateHistoryMapper.insert(operateHistory);
        }catch (DuplicateKeyException e){
            log.warn(operationDesc + ",上传日志重复,入参,{}", uploadLogBO);
            return GetResult.getResultSuccess("上传日志重复");
        }

        Organization updateLastTime = new Organization();
        updateLastTime.setId(organization.getId());
        updateLastTime.setLastTime(String.valueOf(System.currentTimeMillis()));
        organizationMapper.updateOrg(updateLastTime);

        //更新锁状态
        terminalMapper.updateByPrimaryKeySelective(lock);
        //更新钥匙的日志最后上传时间
        key.setLastTime(String.valueOf(System.currentTimeMillis()));
        terminalMapper.updateByPrimaryKeySelective(key);
        operatorLogService.insert(operationDesc, logName, "1", opId, opName, orgId);
        return GetResult.getResultSuccess("导入成功");
    }

    public boolean dateStrIsValid(String rawDateStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = null;
        try {
            // 转化为 Date类型测试判断
            date = dateFormat.parse(rawDateStr);
            return rawDateStr.equals(dateFormat.format(date));
        } catch (ParseException e) {
            log.error("日期格式转换错误:{}", rawDateStr);
            log.error("日期格式转换错误:{}", e.getMessage());
            return false;
        }

    }

    @Override
    public BaseResult<DataGrid<TerminalCopyReslutDTO>> queryAuditInfo(PaginationBO<TerminalCopyDTO> queryBO, HttpServletRequest request) throws Exception {
        TerminalCopyDTO params = queryBO.getParams();
        params.setAuditType(params.getOperateType());
        log.info("查询终端审核信息的入参为{}", JSON.toJSONString(params));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isBlank(params.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            params.setOrgId(org);
        } else {
            //得到本机构的所有下属机构id号
            String org = getOrgIdAllChild(params.getOrgId());
            params.setOrgId(org);
        }
        Operator operatorLog = operatorMapper.getOperatorByOpId(opId);
        PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        List<TerminalCopy> list = terminalCopyMapper.queryCopyList(params);

        List<TerminalCopyReslutDTO> reslutDTOList = new ArrayList<>();
        for (TerminalCopy orgName : list) {
            Organization organization = organizationMapper.getOrganizationByOrgId(orgName.getOrgId());
            orgName.setOrgId(organization.getOrgName());
            Operator operator = operatorMapper.getOperatorByOpId(orgName.getCheckOpId());
            Operator userName = operatorMapper.getOperatorByOpId(orgName.getCreateUser());
            orgName.setCheckOpId(operator.getOpName());
            orgName.setCreateUser(userName.getOpName());
            TerminalCopyReslutDTO dto = new TerminalCopyReslutDTO();
            BeanUtil.copyProperties(orgName, dto);
            dto.setCreateTime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, orgName.getCreateTime()));
            reslutDTOList.add(dto);
        }

        DataGrid dataGrid = PageQuery.getDataGrids(list, reslutDTOList);
        operatorLogService.insert("查询审核设备信息", "查询审核设备", "1", opId, operatorLog.getOpName(), orgId);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public void terminalAuditExport(HttpServletResponse response, TerminalCopyDTO terminalCopyDTO, HttpServletRequest request) {
        try {
            String opId = TokenUtil.getOpId(request.getHeader("token"));
            String orgId = TokenUtil.getOrgId(request.getHeader("token"));
            String opName = TokenUtil.getOpName(request.getHeader("token"));
            operatorLogService.insert("终端审核导出", "终端审核导出", "1", opId, opName, orgId);
            if (StringUtils.isBlank(terminalCopyDTO.getOrgId())) {
                String org = getOrgIdAllChild(orgId);
                terminalCopyDTO.setOrgId(org);
            } else {
                //得到本机构的所有下属机构id号
                String org = getOrgIdAllChild(terminalCopyDTO.getOrgId());
                terminalCopyDTO.setOrgId(org);
            }
            // 执行查询
            List<TerminalCopyExport> list = terminalCopyMapper.terminalAuditExport(terminalCopyDTO);
            if (list == null || list.isEmpty()) {
                throw new RuntimeException("无数据无需导出");
            }
            String title = null;
            String[] headers = null;
            List<Object[]> dataList = null;
            //钥匙
            if (terminalCopyDTO.getType().equals("0")) {
                title = "钥匙审核导出" + Math.random() + ".xls";
                headers = new String[]{"终端名称", "所属机构", "审核类型", "创建人", "审核人", "审核状态", "mac地址", "终端种类", "钥匙种类", "终端状态", "创建时间", "备注"};
                String[] finalHeaders = headers;
                dataList = list.stream().map(keyCopy -> {
                    Object[] obj = new Object[finalHeaders.length];
                    obj[0] = keyCopy.getName();
                    obj[1] = keyCopy.getOrgName();
                    obj[2] = keyCopy.getAuditType();
                    obj[3] = keyCopy.getCreateUserName();
                    obj[4] = keyCopy.getCheckOpName();
                    obj[5] = keyCopy.getIsCheck();
                    obj[6] = keyCopy.getMac();
                    obj[7] = keyCopy.getType();
                    obj[8] = keyCopy.getKeyType();
                    obj[9] = keyCopy.getStatus();
                    obj[10] = keyCopy.getCreateTime();
                    obj[11] = keyCopy.getRemark();
                    return obj;
                }).collect(toList());
            } else if (terminalCopyDTO.getType().equals("1")) {
                title = "锁审核导出" + Math.random() + ".xls";
                headers = new String[]{"终端名称", "所属机构", "审核类型", "创建人", "审核人", "审核状态", "锁类型", "锁场景", "日志翻转", "创建时间", "备注"};
                String[] finalHeaders = headers;
                dataList = list.stream().map(keyCopy -> {
                    Object[] obj = new Object[finalHeaders.length];
                    obj[0] = keyCopy.getName();
                    obj[1] = keyCopy.getOrgName();
                    obj[2] = keyCopy.getAuditType();
                    obj[3] = keyCopy.getCreateUserName();
                    obj[4] = keyCopy.getCheckOpName();
                    obj[5] = keyCopy.getIsCheck();
                    obj[6] = keyCopy.getLockType();
                    obj[7] = keyCopy.getMissionType();
                    obj[8] = keyCopy.getReversion();
                    obj[9] = keyCopy.getCreateTime();
                    obj[10] = keyCopy.getRemark();
                    return obj;
                }).collect(toList());
            } else if (terminalCopyDTO.getType().equals("2")) {
                title = "尾箱审核导出" + Math.random() + ".xls";
                headers = new String[]{"终端名称", "尾箱编号", "所属机构", "任务状态", "尾箱场景", "尾箱种类", "尾箱电量", "经纬度", "异常", "审核类型", "创建人", "审核人",
                        "审核状态", "门磁开关", "门状态", "尾箱绑定锁1", "锁1状态", "尾箱绑定锁2", "锁2状态", "状态", "备注", "创建时间"};
                String[] finalHeaders = headers;
                dataList = list.stream().map(keyCopy -> {
                    Object[] obj = new Object[finalHeaders.length];
                    obj[0] = keyCopy.getName();
                    obj[1] = keyCopy.getTrunkSn();
                    obj[2] = keyCopy.getOrgName();
                    obj[3] = keyCopy.getTaskStatus();
                    obj[4] = keyCopy.getTrunkMissionType();
                    obj[5] = keyCopy.getTrunkType();
                    obj[6] = keyCopy.getElectricity();
                    obj[7] = keyCopy.getCoordinates();
                    obj[8] = keyCopy.getTrunkError();
                    obj[9] = keyCopy.getAuditType();
                    obj[10] = keyCopy.getCreateUserName();
                    obj[11] = keyCopy.getCheckOpName();
                    obj[12] = keyCopy.getIsCheck();
                    obj[13] = keyCopy.getOpenStatus();
                    obj[14] = keyCopy.getDoorStatus();
                    obj[15] = keyCopy.getTrunkLockOneName();
                    obj[16] = keyCopy.getTrunkLockOneStatus();
                    obj[17] = keyCopy.getTrunkLockTwoName();
                    obj[18] = keyCopy.getTrunkLockTwoStatus();
                    obj[19] = keyCopy.getStatus();
                    obj[20] = keyCopy.getRemark();
                    obj[21] = keyCopy.getCreateTime();
                    return obj;
                }).collect(toList());
            } else if (terminalCopyDTO.getType().equals("3")) {
                //PDA 暂无数据
                title = "PDA审核导出" + Math.random() + ".xls";
                headers = new String[]{"终端名称", "PDA编号", "所属机构名称", "PDA类型", "lme号", "是否超出电子围栏使用", "创建人", "审核类型", "审核人", "审核状态", "创建时间", "备注"};
                String[] finalHeaders = headers;
                dataList = list.stream().map(keyCopy -> {
                    Object[] obj = new Object[finalHeaders.length];
                    obj[0] = keyCopy.getName();
                    obj[1] = keyCopy.getPdaId();
                    obj[2] = keyCopy.getOrgName();
                    obj[3] = keyCopy.getPdaType();
                    obj[4] = keyCopy.getImeiId();
                    obj[5] = keyCopy.getOverUser();
                    obj[6] = keyCopy.getCreateUserName();
                    obj[7] = keyCopy.getAuditType();
                    obj[8] = keyCopy.getCheckOpName();
                    obj[9] = keyCopy.getIsCheck();
                    obj[10] = keyCopy.getCreateTime();
                    obj[11] = keyCopy.getRemark();
                    return obj;
                }).collect(toList());
            } else if (terminalCopyDTO.getType().equals("4")) {
                //RFID 暂无数据
                title = "RFID审核导出" + Math.random() + ".xls";
                headers = new String[]{"终端名称", "设备编号", "所属机构", "审核类型", "创建人", "审核人", "审核状态", "创建时间", "备注"};
                String[] finalHeaders = headers;
                dataList = list.stream().map(keyCopy -> {
                    Object[] obj = new Object[finalHeaders.length];
                    obj[0] = keyCopy.getName();
                    obj[1] = keyCopy.getRfidSn();
                    obj[2] = keyCopy.getOrgName();
                    obj[3] = keyCopy.getAuditType();
                    obj[4] = keyCopy.getCreateUserName();
                    obj[5] = keyCopy.getCheckOpName();
                    obj[6] = keyCopy.getIsCheck();
                    obj[7] = keyCopy.getCreateTime();
                    obj[8] = keyCopy.getRemark();
                    return obj;
                }).collect(toList());
            }


            OutputStream out = null;
            // 防止中文乱码
            String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
            response.setContentType("octets/stream");
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            ExcelOutput ex = new ExcelOutput(title, headers, dataList);
            ex.export(out);
            log.info("终端审核导出");
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            HeaderResult.setFailHeader(request, response, e.getMessage());
        }
    }

    @Override
    public BaseResult<Map<String, TerminalCopy>> selectAuditInfo(TerminalCopyDTO terminalCopyDTO, HttpServletRequest request) throws Exception {
        log.info("查询终端审核详情的入参为{}", JSON.toJSONString(terminalCopyDTO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operatorLog = operatorMapper.getOperatorByOpId(opId);
        operatorLogService.insert("查询终端审核详情", "查询设备", "1", opId, operatorLog.getOpName(), orgId);
        Map<String, TerminalCopy> map = new HashMap<>();
        TerminalCopy resultCopy = terminalCopyMapper.selectByPrimaryKey(terminalCopyDTO.getId());
        Organization organization = organizationMapper.getOrganizationByOrgId(resultCopy.getOrgId());
        Operator operator = operatorMapper.getOperatorByOpId(resultCopy.getCheckOpId());
        Operator userName = operatorMapper.getOperatorByOpId(resultCopy.getCreateUser());
        resultCopy.setCheckOpId(operator.getOpName());
        resultCopy.setCreateUser(userName.getOpName());
        resultCopy.setOrgId(organization.getOrgName());
        //oldData-审核前，newDate-审核后
        if (AuditTypeEnum.ADD.getCode().equals(resultCopy.getAuditType())) {
            map.put("oldData", null);
            map.put("newDate", resultCopy);
            return GetResult.getResult(map);
        } else if (AuditTypeEnum.DELETE.getCode().equals(resultCopy.getAuditType())) {
            map.put("oldData", resultCopy);
            map.put("newDate", null);
            return GetResult.getResult(map);
        } else {
            List<TerminalCopy> list = terminalCopyMapper.selectByAuditByTerId(terminalCopyDTO.getId(), resultCopy.getTerminalId());
            if (!list.isEmpty()) {
                Organization oldDataOrg = organizationMapper.getOrganizationByOrgId(list.get(0).getOrgId());
                list.get(0).setOrgId(oldDataOrg.getOrgName());
                map.put("oldData", list.get(0));
            } else if (AuditTypeEnum.ENABLE.getCode().equals(resultCopy.getAuditType())) {
                TerminalCopy oldData = new TerminalCopy();
                BeanUtil.copyProperties(resultCopy, oldData);
                oldData.setStatus("1");
                map.put("oldData", oldData);
            } else {
                Terminal terminal = terminalMapper.selectByPrimaryKey(resultCopy.getTerminalId());
                Organization organization1 = organizationMapper.getOrganizationByOrgId(terminal.getOrgId());
                terminal.setOrgId(organization1.getOrgName());
                TerminalCopy oldData = new TerminalCopy();
                BeanUtil.copyProperties(terminal, oldData);
                oldData.setStatus("1");
                map.put("oldData", oldData);
            }
            map.put("newDate", resultCopy);
            return GetResult.getResult(map);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult<TerminalCopy> audit(TerminalCopyDTO terminalCopyDTO, HttpServletRequest request) {
        log.info("审核入参为{}", JSON.toJSONString(terminalCopyDTO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        operatorLogService.insert("审核终端", "审核终端", "1", opId, operator.getOpName(), orgId);
        TerminalCopy terminalCopy = terminalCopyMapper.selectByPrimaryKey(terminalCopyDTO.getId());
        Organization organization = organizationMapper.getOrganizationByOrgId(terminalCopy.getOrgId());
        if (ObjectUtil.isNull(organization)) {
            return GetResult.getResultFail("终端" + terminalCopy.getName() + "所属机构不存在，无法审核");
        }
        //判断当前登录用户是否是指定审核人
        if (!opId.equals(terminalCopy.getCheckOpId())) {
            return GetResult.getResultFail("当前用户没有审核权限！");
        }
        Terminal select = terminalMapper.selectByPrimaryKey(terminalCopy.getTerminalId());
        if (ObjectUtil.isNotNull(select)) {
            //判断当前终端(类型为锁终端 和尾箱终端判断)是否存在已生效任务
            if (IsCheckEnum.PASS_CHECKED.getCode().equals(terminalCopyDTO.getIsCheck()) && TerminalTypeEnum.LOCK.getCode().equals(terminalCopy.getType())) {
                //获取锁具sn码
                String terminalSn = select.getTerminalSn();
                //修改锁具调用自动删除锁具关联的任务
                if (!select.getOrgId().equals(terminalCopy.getOrgId())
                        || (StrUtil.isNotBlank(select.getMissionType()) && StrUtil.isNotBlank(terminalCopy.getMissionType()) && !select.getMissionType().equals(terminalCopy.getMissionType()))
                        || (StrUtil.isNotBlank(select.getLockType()) && StrUtil.isNotBlank(terminalCopy.getLockType()) && !select.getLockType().equals(terminalCopy.getLockType()))
                        || (StrUtil.isNotBlank(select.getAdminId()) && StrUtil.isNotBlank(terminalCopy.getAdminId()) && !select.getAdminId().equals(terminalCopy.getAdminId()))
                ) {
                    znsTaskMapper.deleteBYSn(terminalSn);
                }
                ////查询是否有关于该锁具任务
                //Integer count = znsTaskMapper.selectConut(terminalSn);
                //if (count > 0) {
                //    return GetResult.getResultFail("审核失败,终端" + select.getName() + "存在未失效任务");
                //}
            }
        }

        //审核状态 0未审核 1复核通过 2审核不通过")
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(terminalCopyDTO.getIsCheck())) {
            Terminal terminal = new Terminal();
            BeanUtil.copyProperties(terminalCopy, terminal);
            if (AuditTypeEnum.ADD.getCode().equals(terminalCopy.getAuditType())) {
                terminal.setId(null);
                terminal.setIsInit("0");
                terminal.setLastTime("0");
                terminalMapper.insert(terminal);
                Integer terminalId = terminalMapper.getLastInsertId();
                terminalMapper.updateTerminalSn(terminalId);

//                Terminal terminal1 = terminalMapper.selectByName(terminal.getName());
                TerminalCopy copy = new TerminalCopy();
                copy.setId(terminalCopyDTO.getId());
                copy.setTerminalId(terminalId);
                copy.setIsCheck(terminalCopyDTO.getIsCheck());
                terminalCopyMapper.updateById(copy);
            } else if (AuditTypeEnum.DELETE.getCode().equals(terminalCopy.getAuditType())) {
                terminalMapper.updateById(String.valueOf(terminalCopy.getTerminalId()));
                TerminalCopy copy = new TerminalCopy();
                copy.setId(terminalCopyDTO.getId());
                copy.setIsCheck(terminalCopyDTO.getIsCheck());
                copy.setIsDeleted("1");
                if ("0".equals(terminalCopy.getType())) {
                    terminalCopyMapper.deleteByMac(terminalCopy.getMac());
                } else {
                    terminalCopyMapper.deleteByTerId(String.valueOf(terminalCopyDTO.getId()));
                }
            } else {
                //锁具停用时删除所有任务
                if (AuditTypeEnum.DISABLE.getCode().equals(terminalCopy.getAuditType())) {
                    znsTaskMapper.deleteBYSn(select.getTerminalSn());
                }
                Terminal update = new Terminal();
                BeanUtil.copyProperties(terminalCopy, update);
                //锁具修改为通用锁设置关联人员为空
                if (LockTypeEnum.EMPLOYEE_GENERAL.getCode().equals(terminalCopy.getLockType())) {
                    update.setAdminId(null);
                }
                update.setId(terminalCopy.getTerminalId());
                terminalMapper.updateByPrimaryKeySelective(update);
            }
            TerminalCopy updateStatus = new TerminalCopy();
            updateStatus.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
            updateStatus.setId(terminalCopyDTO.getId());
            if (!StringUtils.isEmpty(terminalCopyDTO.getAuditDesc())) {
                updateStatus.setAuditDesc(terminalCopyDTO.getAuditDesc());
            }
            terminalCopyMapper.updateByPrimaryKeySelective(updateStatus);
        } else {
            TerminalCopy copy = new TerminalCopy();
            copy.setId(terminalCopyDTO.getId());
            copy.setIsCheck(IsCheckEnum.NOT_PASS_CHECKED.getCode());
            if (!StringUtils.isEmpty(terminalCopyDTO.getAuditDesc())) {
                copy.setAuditDesc(terminalCopyDTO.getAuditDesc());
            }
            terminalCopyMapper.updateByPrimaryKeySelective(copy);
        }
        return GetResult.getResultSuccess("审核成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult<TerminalCopy> batchAudit(TerminalAuditBO terminalAuditBO, HttpServletRequest request) {
        String[] ids = terminalAuditBO.getId().split(",");
        for (String id : ids) {
            TerminalCopyDTO auditBO = new TerminalCopyDTO();
            auditBO.setId(Integer.valueOf(id));
            auditBO.setIsCheck(String.valueOf(terminalAuditBO.getAuditFlag()));
            auditBO.setAuditDesc(terminalAuditBO.getAuditDesc());
            BaseResult result = audit(auditBO, request);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        return GetResult.getResultSuccess("审核成功");
    }

    @Override
    public BaseResult<List<OrgDTO>> getOperateBySn(HttpServletRequest request, TerminalSnBO terminalSnBO) {
        String[] terminalSns = terminalSnBO.getTerminalSn().split(",");
        List<OrgDTO> operatorList = new ArrayList<>();
        for (String terminalSn : terminalSns) {
            Terminal terminal = terminalMapper.getTerminalBySn(terminalSn, TerminalTypeEnum.LOCK.getCode());
            if (ObjectUtil.isNotNull(terminal)) {
                Operator operator = operatorMapper.getOperatorByOpId(terminal.getAdminId());
                OrgDTO orgDto = new OrgDTO();
                orgDto.setOrgId(operator.getOrgId());
                orgDto.setOpId(String.valueOf(operator.getId()));
                orgDto.setOpName(operator.getOpName());
                orgDto.setOpRealName(operator.getOpRealname());
                orgDto.setRoleName(operator.getRoleName());
                operatorList.add(orgDto);
            }
        }
        //list去重
        operatorList = operatorList.stream().distinct().collect(Collectors.toList());
        return GetResult.getResult(operatorList);
    }

    @Override
    public BaseResult initLock(TerminalInitBO initBO, HttpServletRequest request) {
        Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(initBO.getId()));
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("终端信息不存在");
        }
        Terminal initTerminal = new Terminal();
        initTerminal.setId(terminal.getId());
        initTerminal.setIsInit("1");
        terminalMapper.updateByPrimaryKeySelective(initTerminal);
        return GetResult.getResultSuccess("初始化成功");
    }

    @Override
    public BaseResult resetLock() {
        List<Terminal> terminal = terminalMapper.getResetLock();
        if (terminal != null && terminal.size() > 0) {
            for (Terminal ter : terminal) {
                //清除锁具在新机构中的开锁任务
                TaskFindBO taskFindBO = new TaskFindBO();
                taskFindBO.setOrgId(ter.getOrgId());
                taskFindBO.setLockSn(ter.getTerminalSn());
                taskFindBO.setTimeScopeBegin(ter.getStartTime());
                taskFindBO.setTimeScopeEnd(ter.getEffectTime());
                List<TaskZNSDTO> taskZNSDTOS = znsTaskMapper.selectByCon(taskFindBO);
                if (CollectionUtil.isNotEmpty(taskZNSDTOS)) {
                    List<String> taskIds = taskZNSDTOS.stream().map(TaskZNSDTO::getTaskId).collect(toList());
                    String[] split = new String[taskIds.size()];
                    split = taskIds.toArray(split);
                    znsTaskMapper.updateTaskState(split);
                }

                Terminal update = new Terminal();
                update.setId(ter.getId());
                update.setOrgId(ter.getOldOrg());
                update.setStartTime(null);
                update.setEffectTime(null);
                terminalMapper.updateByPrimaryKeySelective(update);
            }
        }
        return GetResult.getResult(null);
    }

    @Override
    public BaseResult checkKey(TerminalSignBO signBO, HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        List<String> orgIds = null;
        try {
            List<Organization> orgs = organizationService.getOrgIds(orgId);
            orgIds = new ArrayList<>();
            for (Organization org : orgs) {
                orgIds.add(org.getOrgId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Terminal terminal = terminalMapper.getTerminalByMacAndOrgIds(signBO.getMac(), orgIds);
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("本机构及下属机构不存在该钥匙");
        }
        return GetResult.getResult(null);
    }

    @Override
    public BaseResult<List<OperatorDTO>> findOperatorByOrg(OrgBO orgBO, HttpServletRequest request) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("您未登录系统！");
        }

        List<OperatorDTO> list = operatorMapper.findOperatorByOrg(orgBO.getOrgId(), PopedomEnum.OPENLOCK.getPopemdomId());
        BaseResult<List<OperatorDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(list);
        objectBaseResult.setDataMessage("当前机构下开锁权限人员");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult<List<OperatorDTO>> findOperatorByOrgAndTaskType(SingleLockBo singleLockBo, HttpServletRequest request) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("您未登录系统！");
        }

        List<OperatorDTO> list = operatorMapper.findOperatorByOrgAndTaskType(singleLockBo.getOrgId(), singleLockBo.getTaskTypeId(), PopedomEnum.OPENLOCK.getPopemdomId());
        BaseResult<List<OperatorDTO>> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(list);
        objectBaseResult.setDataMessage("当前机构下开锁权限人员");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public BaseResult getCurrentTime() {
        String curTime = cn.hutool.core.date.DateUtil.format(new Date(), "yyyyMMddHHmmss");
        return GetResult.getResult(curTime);
    }

    /**
     * 添加审核信息
     *
     * @param terminal  终端信息
     * @param isCheck   审核状态 0待复核 1已复核
     * @param checkOpId 申请复核人，不限制时填0
     * @param auditType 复核类型 1添加 2修改 3删除
     **/
    private void addTerminalCopy(Terminal terminal, String isCheck, String checkOpId, String auditType) {
        //查询该终端是否存在添加审核
        TerminalCopy terminalCopy = new TerminalCopy();
        terminalCopy.setType(terminal.getType());
        terminalCopy.setName(terminal.getName());
        terminalCopy.setKeyType(terminal.getKeyType());
        terminalCopy.setMac(terminal.getMac());
        terminalCopy.setOrgId(terminal.getOrgId());
        terminalCopy.setOverUser(terminal.getOverUser());
        terminalCopy.setAdminId(terminal.getAdminId());
        terminalCopy.setJumpLock(terminal.getJumpLock());
        terminalCopy.setRemark(terminal.getRemark());
        terminalCopy.setCreateTime(terminal.getCreateTime());
        terminalCopy.setCreateUser(terminal.getCreateUser());
        terminalCopy.setStatus(terminal.getStatus());
        terminalCopy.setTerminalId(terminal.getId());
        terminalCopy.setAuditType(auditType);
        terminalCopy.setIsCheck(isCheck);
        terminalCopy.setCheckOpId(checkOpId);
        terminalCopy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        terminalCopy.setTrunkSn(terminal.getTrunkSn());
        terminalCopy.setTrunkType(terminal.getTrunkType());
        terminalCopy.setImeiid(terminal.getImeiid());
        terminalCopy.setEmailid(terminal.getEmailid());
        terminalCopy.setLockStatus(terminal.getLockStatus());
        terminalCopy.setReversion(terminal.getReversion());
        terminalCopy.setLockType(terminal.getLockType());
        terminalCopy.setMissionType(terminal.getMissionType());
        terminalCopy.setTrunkMissionType(terminal.getTrunkMissionType());
        terminalCopy.setTaskStatus(terminal.getTaskStatus());
        terminalCopy.setTrunkError(terminal.getTrunkError());
        terminalCopy.setElectricity(terminal.getElectricity());
        terminalCopy.setCoordinates(terminal.getCoordinates());
        terminalCopy.setOpenStatus(terminal.getOpenStatus());
        terminalCopy.setDoorStatus(terminal.getDoorStatus());
        terminalCopy.setLockStatusOne(terminal.getLockStatusOne());
        terminalCopy.setLockStatusTwo(terminal.getLockStatusTwo());
        terminalCopy.setPdaid(terminal.getPdaid());
        terminalCopy.setPdatype(terminal.getPdatype());
        terminalCopy.setRfidsn(terminal.getRfidsn());
        terminalCopy.setCreateTime(new Date());
        terminalCopy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        if (terminalCopy.getId() != null) {
            terminalCopyMapper.updateByPrimaryKey(terminalCopy);
        } else {
            terminalCopyMapper.insert(terminalCopy);
        }
    }

    @Override
    public BaseResult<Integer> selectCount(TerminalDTO dto, HttpServletRequest request) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        Integer count = terminalCopyMapper.selectCount(dto.getOrgId());
        return GetResult.getResult(count);
    }

    @Override
    public BaseResult openSwitch(TerminalDTO dto, HttpServletRequest request) {
        Terminal terminal = new Terminal();
        terminal.setOpenStatus(dto.getOpenStatus());
        terminal.setId(dto.getId());
        terminalMapper.updateByPrimaryKey(terminal);
        return GetResult.getResultSuccess("修改或关闭成功");
    }

    @Override
    public BaseResult<Terminal> track(TerminalDTO dto, HttpServletRequest request) {
        Terminal result = terminalMapper.selectByPrimaryKey(dto.getId());
        return GetResult.getResult(result);
    }

    @Override
    public void openOne(String id) {
        List<Terminal> list = terminalMapper.queryByTrunkLock(id, id);
        List<String> oneList = new ArrayList<>();
        List<String> twoList = new ArrayList<>();
        for (Terminal terminal : list) {
            if (id.equals(terminal.getTrunkLockOne())) {
                oneList.add(String.valueOf(terminal.getId()));
            } else if (id.equals(terminal.getTrunkLockTwo())) {
                twoList.add(String.valueOf(terminal.getId()));
            }
        }

        terminalMapper.updateByTrunkLockOne(oneList);
        terminalMapper.updateByTrunkLockTwo(oneList);
    }

    @Override
    public BaseResult openTwo(TerminalDTO dto, HttpServletRequest request) {
        Terminal terminal = new Terminal();
        terminal.setLockStatusTwo(dto.getLockStatusTwo());
        terminal.setId(dto.getId());
        terminalMapper.updateByPrimaryKey(terminal);
        return GetResult.getResultSuccess("修改或关闭成功");
    }

    @Override
    public BaseResult openThree(TerminalDTO dto, HttpServletRequest request) {
        Terminal terminal = new Terminal();
        terminal.setDoorStatus(dto.getDoorStatus());
        terminal.setId(dto.getId());
        terminalMapper.updateByPrimaryKey(terminal);
        return GetResult.getResultSuccess("修改或关闭成功");
    }

    @Override
    public BaseResult importInfo(HttpServletRequest request, TerminalCopyDTO terminalDTO, MultipartFile multipartFile) throws Exception {
        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        if (".xls".equals(suffix) || ".xlsx".equals(suffix)) {
            InputStream inputStream = multipartFile.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            HSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet != null) {
                List<TerminalAddBO> addBOList = new ArrayList<>();
                System.out.println(sheet.getLastRowNum() + "==============");
                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    TerminalAddBO dto = new TerminalAddBO();
                    // 从第二行开始得到每行的值
                    HSSFRow row = sheet.getRow(i);
                    if ("0".equals(terminalDTO.getType())) {
                        row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String name = row.getCell(0).getStringCellValue();
                        row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String keyType = row.getCell(1).getStringCellValue();
                        row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String orgId = row.getCell(2).getStringCellValue();
                        row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String mac = row.getCell(3).getStringCellValue();
                        String overUser = null;
                        if (row.getCell(4) != null) {
                            row.getCell(4).setCellType(CellType.STRING);
                            overUser = row.getCell(4).getStringCellValue();
                        }
                        String remark = null;
                        if (row.getCell(5) != null) {
                            row.getCell(5).setCellType(CellType.STRING);
                            remark = row.getCell(5).getStringCellValue();
                        }
                        dto.setType(terminalDTO.getType());
                        dto.setName(name);
                        dto.setKeyType(keyType);
                        dto.setOrgId(orgId);
                        dto.setMac(mac);
                        dto.setOverUser(overUser);
                        dto.setRemark(remark);
                    } else if ("1".equals(terminalDTO.getType())) {
                        //headers = new String[]{"终端名称", "锁种类", "所属机构", "锁场景", "柜员id", "日志翻转","备注"};
                        row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String name = row.getCell(0).getStringCellValue();
                        row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String lockType = row.getCell(1).getStringCellValue();
                        row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String orgId = row.getCell(2).getStringCellValue();
                        row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String missionType = row.getCell(3).getStringCellValue();
                        String admin = "";
                        String remak = "";
                        if (row.getCell(4) != null) {
                            row.getCell(4).setCellType(CellType.STRING);
                            admin = row.getCell(4).getStringCellValue();
                            admin = operatorMapper.queryByOpName(admin);
                        }
                        row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String reversion = row.getCell(5).getStringCellValue();
                        row.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String jumpLock = row.getCell(6).getStringCellValue();
                        if (row.getCell(7) != null) {
                            row.getCell(7).setCellType(CellType.STRING);
                            remak = row.getCell(7).getStringCellValue();
                        }
                        dto.setType(terminalDTO.getType());
                        dto.setName(name);
                        dto.setLockType(lockType);
                        dto.setOrgId(orgId);
                        dto.setMissionType(missionType);
                        dto.setJumpLock(jumpLock);
                        if (!StringUtils.isEmpty(admin)) {
                            dto.setAdminId(admin);
                        }
                        dto.setReversion(reversion);
                        if (!StringUtils.isEmpty(remak)) {
                            dto.setRemark(remak);
                        }
                    } else if ("2".equals(terminalDTO.getType())) {
                        //终端名称","所属机构","尾箱种类","尾箱imei号","电子标签id","尾箱场景","尾箱状态","尾箱编号","备注,绑定锁id1，绑定锁id2
                        row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String name = row.getCell(0).getStringCellValue();
                        row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String orgId = row.getCell(1).getStringCellValue();
                        row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String trunkType = row.getCell(2).getStringCellValue();
                        String trunkImei = null;
                        if (row.getCell(3) != null) {
                            row.getCell(3).setCellType(CellType.STRING);
                            trunkImei = row.getCell(3).getStringCellValue();
                        }
                        String emil = null;
                        String trunkStatus = null;
                        String remak = null;
                        if (row.getCell(4) != null) {
                            row.getCell(4).setCellType(CellType.STRING);
                            emil = row.getCell(4).getStringCellValue();
                        }
                        row.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String trunkMissionType = row.getCell(5).getStringCellValue();
                        if (row.getCell(6) != null) {
                            row.getCell(6).setCellType(CellType.STRING);
                            trunkStatus = row.getCell(6).getStringCellValue();
                        }
                        row.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String trunkSn = row.getCell(7).getStringCellValue();
                        String overUser = "1";
                        if (row.getCell(8) != null) {
                            row.getCell(8).setCellType(CellType.STRING);
                            overUser = row.getCell(8).getStringCellValue();
                        }


                        if (row.getCell(9) != null) {
                            row.getCell(9).setCellType(CellType.STRING);
                            remak = row.getCell(9).getStringCellValue();
                        }
                        String lockOne = null;
                        String lockTwo = null;
                        if (row.getCell(10) != null) {
                            row.getCell(10).setCellType(CellType.STRING);
                            lockOne = row.getCell(10).getStringCellValue();
                            Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(lockOne));
                            if (null == terminal) {
                                return GetResult.getResultFail("第" + (i + 1) + "条数据错误,绑定锁id1不存在");
                            }
                            lockOne = String.valueOf(terminal.getId());
                        }
                        if (row.getCell(11) != null) {
                            row.getCell(11).setCellType(CellType.STRING);
                            lockTwo = row.getCell(11).getStringCellValue();
                            Terminal terminal = terminalMapper.selectByPrimaryKey(Integer.valueOf(lockTwo));
                            if (null == terminal) {
                                return GetResult.getResultFail("第" + (i + 1) + "条数据错误,绑定锁id2不存在");
                            }
                            lockTwo = String.valueOf(terminal.getId());
                        }


                        //终端名称","所属机构","尾箱种类","尾箱imei号","电子标签id","尾箱场景","尾箱状态","尾箱编号","备注
                        dto.setType(terminalDTO.getType());
                        dto.setName(name);
                        dto.setOrgId(orgId);
                        dto.setTrunkLockOne(lockOne);
                        dto.setTrunkLockTwo(lockTwo);
                        dto.setTrunkType(trunkType);
                        if (!StringUtils.isEmpty(trunkImei)) {
                            dto.setImeiid(trunkImei);
                        }
                        dto.setEmailid(emil);
                        dto.setTaskStatus(trunkStatus);
                        dto.setTrunkMissionType(trunkMissionType);
                        dto.setTrunkSn(trunkSn);
                        if (!StringUtils.isEmpty(remak)) {
                            dto.setRemark(remak);
                        }
                        dto.setCheckOpId(terminalDTO.getCheckOpId());
                        dto.setIsCheck(terminalDTO.getIsCheck());
                        dto.setOverUser(overUser);
                    } else if (TerminalTypeEnum.PDA.getCode().equals(terminalDTO.getType())) {
                        //终端名称","所属机构","imei号","PDA类型","PDA编号","是否超出电子围栏使用","备注
                        row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String name = row.getCell(0).getStringCellValue();
                        row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String orgId = row.getCell(1).getStringCellValue();
                        String emil = null;
                        String remak = null;
                        String pdaSn = null;
                        if (row.getCell(2) != null) {
                            row.getCell(2).setCellType(CellType.STRING);
                            emil = row.getCell(2).getStringCellValue();
                        }
                        row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String pdaType = row.getCell(3).getStringCellValue();
                        if (row.getCell(4) != null) {
                            row.getCell(4).setCellType(CellType.STRING);
                            pdaSn = row.getCell(4).getStringCellValue();
                        }
                        String overUser = null;
                        if (row.getCell(5) != null) {
                            row.getCell(5).setCellType(CellType.STRING);
                            overUser = row.getCell(5).getStringCellValue();
                        }
                        if (row.getCell(6) != null) {
                            row.getCell(6).setCellType(CellType.STRING);
                            remak = row.getCell(6).getStringCellValue();
                        }
                        dto.setName(name);
                        dto.setOrgId(orgId);
                        dto.setImeiid(emil);
                        dto.setPdatype(pdaType);
                        dto.setPdaid(pdaSn);
                        dto.setOverUser(overUser);
                        dto.setRemark(remak);
                        dto.setType(terminalDTO.getType());
                    } else if (TerminalTypeEnum.RFID.getCode().equals(terminalDTO.getType())) {
                        //终端名称","所属机构","设备编号","备注
                        row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String name = row.getCell(0).getStringCellValue();
                        row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String orgId = row.getCell(1).getStringCellValue();
                        String remak = null;
                        row.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellType(CellType.STRING);
                        String pdaSn = row.getCell(2).getStringCellValue();
                        if (row.getCell(3) != null) {
                            row.getCell(3).setCellType(CellType.STRING);
                            remak = row.getCell(3).getStringCellValue();
                        }
                        dto.setType(terminalDTO.getType());
                        dto.setOrgId(orgId);
                        dto.setRfidsn(pdaSn);
                        dto.setRemark(remak);
                        dto.setName(name);
                    }
                    addBOList.add(dto);
                }
                int flag = 0;
                String msg = null;
                String errorMsg = "";
                for (int i = 0; i < addBOList.size(); i++) {
                    try {
                        TerminalAddBO terminalAddBO = addBOList.get(i);
                        TerminalAddImportBO terminalAddImportBO
                                = BeanUtil.copyProperties(terminalAddBO, TerminalAddImportBO.class);
                        ValidatorUtils.beanValidate(terminalAddImportBO);
                        addImportTerminal(terminalAddBO, request);
                    } catch (Exception e) {
                        log.info("终端信息导入错误信息={}", e.getMessage());
                        errorMsg = e.getMessage();
                        flag++;
                        if (StringUtil.isEmpty(msg)) {
                            msg = String.valueOf(i + 1);
                        } else {
                            msg = msg + "," + (i + 1);
                        }
                    }
                }
                if (flag == 0) {
                    return GetResult.getResultSuccess("导入成功");
                } else {
                    return GetResult.getResultFail("第" + msg + "条数据错误" + errorMsg + "，导入失败");
                }
            }
            return GetResult.getResultSuccess("导入成功");

        } else {
            return GetResult.getResultFail("文件类型只支持.xls 与.xlsx");
        }
    }

    @Override
    public BaseResult saveTrunkData(TerminalDTO dto, HttpServletRequest request) {
        return null;
    }

    public String getOrgIdAllChild(String orgId) throws Exception {
        List<Organization> orgList = organizationService.getOrgIds(orgId);
        StringBuilder sb = new StringBuilder();
        for (Organization organization : orgList) {
            sb.append(organization.getOrgId()).append(",");
        }
        int size = sb.toString().length() - 1;
        return sb.toString().substring(0, size);
    }

    @Override
    public BaseResult<List<Terminal>> selectLockAll(HttpServletRequest request) {
        List<Terminal> trunkList = terminalMapper.selectAllTrunk();
        List<Integer> idsList = new ArrayList<>();
        for (Terminal id : trunkList) {
            if (!StringUtils.isEmpty(id.getTrunkLockOne())) {
                if (!idsList.contains(id.getTrunkLockOne())) {
                    idsList.add(Integer.valueOf(id.getTrunkLockOne()));
                }
            }
            if (!StringUtils.isEmpty(id.getTrunkLockTwo())) {
                if (!idsList.contains(id.getLockStatusTwo())) {
                    idsList.add(Integer.valueOf(id.getTrunkLockTwo()));
                }
            }
        }
        List<Terminal> list = new ArrayList<>();
        if (!idsList.isEmpty()) {
            list = terminalMapper.selectAll(idsList);
        } else {
            list = terminalMapper.selectAllLock();
        }
        return GetResult.getResult(list);
    }

    @Override
    public BaseResult getDate(HttpServletRequest request) {
        try {
            log.info("物联网第三方平台请求到达");
            request.setCharacterEncoding("UTF8");
            StringBuilder stringBuffer = new StringBuilder();
            String line;
            try {
                BufferedReader bufferedReader = request.getReader();
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            String lineStr = stringBuffer.toString();
            System.out.println("data------:" + lineStr);
            JSONObject jsonObject = JSONObject.parseObject(lineStr);
            if (jsonObject.getJSONObject("payload") != null) {
                String appData = jsonObject.getJSONObject("payload").getString("APPdata");
                //"7E010500048697680432630470000000004400FF323032323037000B01000001AA00A7000A000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016057E";
                String numbers = jsonObject.getString("deviceId");
                //"eb8e9013d9d04b539bbfc4406dbe98ba";
                String data = Base64Jdk.subString(Base64Jdk.decode(appData), "7E", "7E");
                System.out.println("appData------:" + data);
                dataUtilsApk.analysisData(Base64Jdk.hexStr2Bytes(data), numbers);
            }
            return GetResult.getResultSuccess("数据更新成功");
        } catch (Exception e) {
            log.error(ErrMessageConst.SYSTEM_ERROR, e);
            return GetResult.getResultErr();
        }
    }

    @Override
    public BaseResult sign(TerminalSignBO signBO, HttpServletRequest request) {
        Terminal terminal = terminalMapper.getTerminalByMac(signBO.getMac());
        if (ObjectUtil.isNull(terminal)) {
            return GetResult.getResultFail("钥匙信息不存在");
        }
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        String opName = TokenUtil.getOpName(request.getHeader("token"));
        operatorLogService.insert("用户" + opName + "对钥匙" + terminal.getName() + "进行签到", "钥匙签到", "1", opId, opName, orgId);
        terminal.setLastSign(new Date());
        terminalMapper.updateByPrimaryKeySelective(terminal);
        return GetResult.getResultSuccess("签到成功");
    }
}
